<?php
namespace App\Http\Controllers\WebApi\User;

use App\Http\Controllers\WebApi\BaseController;
use App\Http\Service\UserService;
use App\Http\Strategy\UserStrategy;
use Illuminate\Http\Request;
use App\Models\Admin\YzmModel;
use App\Services\Admin\UserService as AdminUserService;
/**
 * 用户基础控制器
 * Class IndexController
 * @package App\Http\Controllers\WebApi\Login
 */
class IndexController extends BaseController
{
    protected $service;

    public function __construct()
    {
        parent::__construct();
        $this->service = new AdminUserService();
    }
    
    public function test()
    {
        $dd = UserService::getUserInfo();
        //dd($dd);
        return "test";
    }

    /**
     * 登陆
     * @param Request $request
     * @param UserStrategy $userStrategy
     * @throws \App\Exceptions\BusinessException
     */
    public function login(Request $request, UserStrategy $userStrategy)
    {
        $param = $request->all();

        $this->webParamValidate(
            $request, [
                'phone' => 'required',
                'pwd' => 'required'
            ]
        );
        $web_access = $request->app_access;
        $web_accessFlag = false;
        if($web_access== $this->web_access){
            $web_accessFlag = true;
        }
        if(!$web_accessFlag){
            return $this->toJson(-99);
        }
        $data = $userStrategy->login($param['phone'], $param['pwd']);
        $uid = $data["uid"];
        $token = $this->accessSet($uid);
        //$model = new AdminUserService();
        $cate = $this->service
            ->getUserType($uid,$data["type"]);
        $retData = ["type"=>$data["type"],"token"=>$token,"cate"=>$cate,"uid"=>$uid];
        $this->success($retData);
    }

    /**
     * 验证码登陆
     * @param Request $request
     * @param UserStrategy $userStrategy
     * @throws \App\Exceptions\BusinessException
     */
    public function codeLogin(Request $request, UserStrategy $userStrategy)
    {
        $this->webParamValidate(
            $request, [
                'phone' => 'required|integer',
                'code' => 'required|integer'
            ]
        );
        //增加验证码比较，zwp
        $resYzm = $this->getYzm($request->phone);
        if(intval($resYzm)!=intval($request->code)){
            return $this->toJson(-7);
        }
        $data = $userStrategy->codeLogin($request->post('phone'), $request->post('code'));
        $uid = $data["uid"];
        $token = $this->accessSet($uid);
        //$model = new AdminUserService();
        $cate = $this->service
            ->getUserType($uid,$data["type"]);
        $retData = ["type"=>$data["type"],"token"=>$token,"cate"=>$cate,"uid"=>$uid];
        $this->success($retData);
    }

    /**
     * 退出
     */
    public function signOut(Request $request)
    {
        if(session("loginUser")->id!=$request->uid){
            return $this->toJson(-99);
        }
        session(["loginUser"=>null]);
        session()->save();
        return $this->success();
        /*
        session()->forget("loginUser");
        $url = url("")."web/index";//重定向到首页，zwp
        return redirect($url);
        */
    }

    /**
     * 注册新用户方法
     * @param Request $request
     * @param UserStrategy $userStrategy
     * @throws \App\Exceptions\BusinessException
     */
    public function register(Request $request, UserStrategy $userStrategy)
    {
        $param = $request->all();

        $this->webParamValidate(
            $request, [
                'phone' => 'required|integer',
                'pwd' => 'required|string',//zwp,修改验证类型为string，
                'code' => 'required|integer'
            ]
        );
        
        $web_access = $request->app_access;
        $web_accessFlag = false;
        if($web_access== $this->web_access){
            $web_accessFlag = true;
        }
    //zwp，验证码校验
        $resYzm = $this->getYzm($request->phone);
        if(intval($request->code)==intval($resYzm)&&$web_accessFlag){
            $userStrategy->addUser($param['phone'], $param['pwd'], $param['code']);
            $uid = $userStrategy->getUid($param["phone"]);
            $token = $this->accessSet($uid);//获取token，zwp
            session(['uid'=>$uid,'token'=>$token]);
            session()->save();
            $data = ["uid"=>$uid,"token"=>$token];
            $this->success($data);
        }else{
            return $this->toJson(-7);
        }
        
    }

    public function getYzm($phone)
    {
        return 1234; //先取消验证码验证
//        $start = strtotime(date('Ymd').'000000');
//        $end = strtotime(date('Ymd').'235959');
        $model = YzmModel::where('phone',$phone)
            ->where('status',2)
//            ->where('created_at','>',$start)
//            ->where('created_at','<=',$end)
            ->where('created_at','>',time()-60*30)
            ->first();
        return $model ? $model->code : '';
    }
    
    /**
     * 重置密码
     * @param Request $request
     * @param UserStrategy $userStrategy
     * @throws \App\Exceptions\BusinessException
     */
    public function resetPassword(Request $request, UserStrategy $userStrategy)
    {
        $param = $request->all();

        $this->webParamValidate(
            $request, [
                'phone' => 'required|integer',
                'pwd' => 'required|string',
                'code' => 'required|integer'
            ]
        );
        //增加验证码验证，zwp
        $resYzm = $this->getYzm($request->phone);
        $flag = $userStrategy->resetPwd($param['phone'], $param['pwd'], $param['code'],$resYzm);
        if(!$flag){
            return $this->toJson(-7);
        }
        $this->success();
    }

    /**
     * 用户设置主题类型
     * @param Request $request
     * @param UserStrategy $userStrategy
     * @throws \App\Exceptions\BusinessException
     */
    public function userSetType(Request $request, UserStrategy $userStrategy)
    {
        $this->validate($request, [
            'type' => 'required|integer',
            'introducer' => 'integer'
        ]);
        $type = $request->get('type');
        if($type==0){
            return $this->toJson(-2);
        }
        $userId = UserService::getUserInfo()['uid'];
        //var_dump($userId);exit();
        $setFlag = $userStrategy->setUserType($userId, $type, $request->get('introducer') ?? 0);
        //zwp，增加返回值判断，以撤销ession
        if($setFlag){
            session(["uid"=>null,"token"=>null]);//session中对应字段置空，好允许重新注册，zwp
            session()->save();
            $this->success();
        }else{
            return $this->toJson(-8);
        }
        
    }
    
    
}